﻿

using CCSSolderUI.Models;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace CCSSolderUI.ViewModels.Dialogs
{
    public class AlarmDialogViewModel : BindableBase, IDialogAware
    {
        #region 变量
        CancellationTokenSource source;
        #endregion
        #region 属性绑定
        private string alarmContent;
        public string AlarmContent
        {
            get { return alarmContent; }
            set { SetProperty(ref alarmContent, value); }
        }
        #endregion
        #region 导航
        public string Title => "报警窗口";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            if (source != null)
            {
                source.Cancel();
            }
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            AlarmContent = parameters.GetValue<string>("Content");
            source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            Run(token);
        }
        #endregion
        #region 功能函数
        private async void Run(CancellationToken token)
        {
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                if (PLCModbus.Instance.Connected)
                {
                    var aa = PLCModbus.Instance.ReadXCoils(2, 1);
                    if (aa != null)
                    {
                        if (aa[0])
                        {
                            RequestClose?.Invoke(new DialogResult());
                            return;
                        }
                    }
                    aa = PLCModbus.Instance.ReadXCoils(0, 1);
                    if (aa != null)
                    {
                        if (aa[0])
                        {
                            RequestClose?.Invoke(new DialogResult());
                            return;
                        }
                    }
                    aa = PLCModbus.Instance.ReadXCoils(1, 1);
                    if (aa != null)
                    {
                        if (aa[0])
                        {
                            RequestClose?.Invoke(new DialogResult());
                            return;
                        }
                    }
                }
                await Task.Delay(100);
            }
        }
        #endregion

    }
}
